package menus_api

import (
	"errors"
	"gin_study_blog/common"
	"gin_study_blog/common/blog_type"
	"gin_study_blog/common/http"
	"gin_study_blog/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type ImageSort struct {
	ImageID uint `json:"image_id"`
	Sort    int  `json:"sort"`
}

type MenusRequest struct {
	Title           string          `json:"title" binding:"required" msg:"请输入菜单名称"` // 菜单名称
	Path            string          `json:"path" binding:"required" msg:"请输入跳转地址"`  // 跳转地址
	Slogan          string          `json:"slogan"`                                 // slogan
	Information     blog_type.Array `json:"information"`                            // 简介
	InformationTime int             `json:"information_time"`                       // 简介的切换时间
	BannerTime      int             `json:"banner_time"`                            // 菜单图片的切换时间为0表示不切换
	Sort            int             `json:"sort"`
	ImageSortList   []ImageSort     `json:"image_sort_list"` // 具体图片的顺序
}

func (MenusApi) MenusCreateView(c *gin.Context) {
	var cr MenusRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		http.FailWithError(err, &cr, c)
		return
	}

	// 重复值判断
	err = common.DB.Take(&models.MenuModel{}, "title = ? AND path = ?", cr.Title, cr.Path).Error
	if err == nil {
		http.FailWithMessage("菜单名称重复", c)
		return
	}
	// 增加 mysql  事务
	if err = common.DB.Transaction(func(tx *gorm.DB) error {
		// 创建banner数据入库 添加完成默认返回主键id
		menuData := &models.MenuModel{
			Title:           cr.Title,
			Path:            cr.Path,
			Slogan:          cr.Slogan,
			Information:     cr.Information,
			InformationTime: cr.InformationTime,
			BannerTime:      cr.BannerTime,
			Sort:            cr.Sort,
		}
		err = tx.Create(menuData).Error
		if err != nil {
			common.Log.Error(err.Error())
			return errors.New("添加菜单失败")
		}
		if len(cr.ImageSortList) == 0 {
			return errors.New("添加成功")
		}
		// 给第三张入库
		menuBannerList := make([]*models.MenuBannerModel, 0)

		for _, sort := range cr.ImageSortList {
			// 需要判断图片是否存在
			menuBannerList = append(menuBannerList, &models.MenuBannerModel{
				MenuID:   menuData.ID,
				BannerID: sort.ImageID,
				Sort:     sort.Sort,
			})
		}
		err = tx.Create(&menuBannerList).Error
		if err != nil {
			common.Log.Error(err.Error())
			return errors.New("菜单图片关联失败")
		}
		return nil
	}); err != nil {
		http.FailWithMessage(err.Error(), c)
		return
	}
	http.FailWithMessage("添加成功", c)
}
